# _*_ coding:utf-8 _*_
from django.db import models
from DjangoUeditor.models import UEditorField
from django.utils import timezone


# Create your models here.
class Column(models.Model):
    column_text = models.CharField(max_length=10)
    update_date = models.DateTimeField(u'更新日期', editable=False, default=timezone.now)
    update_content = models.CharField(u'更新内容概要', max_length=130, editable=True, default='专栏创建。')
    create_date = models.DateTimeField(u'创建日期', editable=False, default=timezone.now)
    article_num = models.IntegerField(default=0, editable=False)
    upload_img = models.ImageField(upload_to='uploads/%Y/%m/%d/', default='NoImage.jpg')
    comment = models.CharField(u'专栏介绍', max_length=100, editable=True, default=u'暂无介绍')

    def __str__(self):
        return self.column_text


class Article(models.Model):
    column = models.ForeignKey(Column, on_delete=models.CASCADE)
    title = models.CharField(u'博客标题', max_length=100)
    category = models.CharField(u"博客标签", max_length=50, blank=True)
    pub_date = models.DateTimeField(u"发布日期", auto_now_add=True, editable=False)
    update_time = models.DateTimeField(u"更新时间", auto_now_add=True, null=True)
    content = UEditorField(u"文章正文", height=300, width=1000, default=u'', blank=True, imagePath="uploads/blog/images/",
                           toolbars='besttome', filePath='uploads/blog/files/')
    author = models.CharField(u"博客作者", max_length=100, default='ximin')
    read_times = models.IntegerField(default=0, editable=False)
    # def save(self, *args, **kwargs):
    #     if self.column is None:  # Set default reference
    #         self.column = Column.objects.get(id=1)
    #     super(Article, self).save(*args, **kwargs)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        c = self.column
        print("self.id:", self.id)
        print("self.content:", self.content)
        if self.id is None:    # 判断是否为发布新博客。
            c.article_num += 1
            c.update_content = self.title + u" 发布。"
            c.save()
        else:
            if self.content != Article.objects.get(id=self.id).content:
                c.update_date = timezone.now()
                c.update_content = self.title + u" 更新。"
                print(self.title + u" 更新。")
                c.save()
        super(Article, self).save(*args, **kwargs)


